<?php
/**
 * Created by PhpStorm.
 * User: UGLY
 * Date: 2017/12/30
 * Time: 18:48
 */

namespace app\mainiu\controller;

use think\Db;
use app\blog\controller\CommonController;
use think\Validate;

class TypeController extends CommonController
{
    //分类管理主页
    public function typeindex()
    {
        echo 'typeindex';
    }
    //分类管理添加
    public function typeadd()
    {
        return $this->fetch();
    }
    //分类添加方法
    public function add()
    {
        $request = request();
        $post = $request->post();
        //要验证的字段
        $rule = [
            'name' => 'require|max:10',
        ];
        $data = [
            'name'=>$post['name'],
            'des'=>$post['des'],
            'time'=>date("Y-m-d H:i:s",time()),
            'aid'=>$_SESSION['think']['ADMIN_ID'],
        ];
        //出错的信息
        $msg = [
            'name.require' => '请填写您的名称',
            'name.max'     => '名称最多不能超过10个字符',
        ];
        $validate = new Validate($rule,$msg);
        if($validate->check($data)){
            if(\db('type')->insert($data)){
                echo 1;
            }else{
                echo 2;
            }
        }else{
            echo $validate->getError();
        }
    }
    //分类管理查看
    public function typewatch()
    {
        return $this->fetch();
    }
    //所有分类方法
    public function returntype()
    {
        //管理员id
        $id = $_SESSION['think']['ADMIN_ID'];
        $data = Db::name('type')->where(['aid'=>$id])->order('id desc')->select();
        if($data){
            echo json_encode($data);
        }else{
            echo 2;
        }
    }
    //分类删除
    public function del()
    {
        $post = request();
        $post = $post->post();
        if(\db('type')->delete($post['id'])){
            echo json_encode(
                [
                    'id'=>$post['id'],
                    'sta'=>1
                ]
            );
        }else{
            echo '删除失败';
        }
    }
    //分类搜索
    public function ser()
    {
        $post = request();
        $post = $post->post();
        //管理员id
        $id = $_SESSION['think']['ADMIN_ID'];
        //模糊匹配
        $where= array('like','%'.$post['text'].'%');
        $data = \db('type')->where(['name|des'=>$where,'aid'=>$id])->select();
        if($data){
            echo json_encode($data);
        }else{
            echo '没有找到任何内容';
        }
    }
}